function [F,inliers] = RANSAC_F(x,xp,dThresh)
% x are the coordinates in image1
% xp are coordinates in image2, both in nx2 size
%dThresh is the distance threshold in pixels, rocomended is 1.5

e = .60;% outlier probability              
p = .99; % probability of finding a sample of data without outliers
s = 8; %we will use the 8pt algorithm
N = log(1 - p)/log(1 - (1 - e)^s);%number of maximum iterations
samplesTaken = 0; %variable that keeps track of the samples that have been tried
bestResErr = Inf; %variable that keeps track of the best error until now
maxInliers = 0; % variable for maximum number of inliers so far
S = size(x,1); %size of the sample
%%%%%%%%DELETE
%dThresh = 1.5;
%%%%%%%/DELETE


while samplesTaken < N
    %select random samples
    samples = randperm(S); %will randomly permutate indexes of the size of putative matches
    %TO DO: make only this randomization every time we ran out of
    %permutated 8 sized collections of indices 
    samples = samples(1:8); %select always the first two
    samplesTaken = samplesTaken + 1;
   
    %compute fundamental matrix using SVD    
    F = Ffromxs_norm(x(samples,:),xp(samples,:));
    
    %determine inliers
    [x_h,xp_h] = euclid2hmg(x,xp);
    L1 = normalizeLine(F*x_h');%convert the epipolar line F*x to normalized so a dot product where w=1 is the distance
    dist1 = abs(dot( xp_h', L1 ));%vector of distances from correspondent points in I2 and epipolar line
    
    L2 = normalizeLine(F' * xp_h');
    dist2 = abs(dot( L2, x_h' ));%vector of distances from correspondent points in I1 and epipolar line
    
    inliers = find( dist1 < dThresh & dist2 < dThresh );
    inlierCount = size(inliers,2);
    if inlierCount > 0
        resErr = sum(dist1(inliers).^2 + dist2(inliers).^2 )/inlierCount;%error calculated only with inliers
        %TODO: use sampson error....why?
    else
        resErr = Inf;
    end
    if inlierCount > maxInliers || (inlierCount == maxInliers && resErr < bestResErr)
        % keep best F found so far
        maxInliers = inlierCount;
        bestResErr = resErr;
        bestF = F;
        bestInliers = inliers;%indices of the inlier matching points
        
        % adaptively update N (Hartley and Zisserman)
        e = 1 - inlierCount/S; %updated probability of outliers
        if e > 0 %handle only positive numbers
            N = log(1 - p)/log(1 - (1 - e)^s);%recalculate N
        else
            N = 1;
        end
    end
end 

F = bestF;
inliers = bestInliers;